
//这个函数在整个wps加载项中是第一个执行的
function OnAddinLoad(ribbonUI){
    if (typeof (wps.ribbonUI) != "object"){
		wps.ribbonUI = ribbonUI
    }
    
    if (typeof (wps.Enum) != "object") { // 如果没有内置枚举值
        wps.Enum = WPS_Enum
    }

    wps.PluginStorage.setItem("EnableFlag", false) //往PluginStorage中设置一个标记，用于控制两个按钮的置灰
    wps.PluginStorage.setItem("ApiEventFlag", false) //往PluginStorage中设置一个标记，用于控制ApiEvent的按钮label

    
    return true
}

var WebNotifycount = 0;
function OnAction(control) {
    const eleId = control.Id
    let data = {};
    let dataObj = '';
    let url = '';
    switch (eleId) {
        case "btnRecycleBoxGold":
            {
                const doc = wps.EtApplication().ActiveWorkbook
                if (!doc) {
                    alert("当前没有打开任何文档")
                    return
                }
                //alert(doc.Name)
                //alert("Huile")

                //let url = getMainURL() + "/kim/recycleBoxGold" + "?1=1"+"&access_token="+access_token();
				//wps.ShowDialog(url, "回碎金", 600 * window.devicePixelRatio, 400 * window.devicePixelRatio, true)
            }
            break;
        case "btnPrintCastingLoss":
            data = wps.PluginStorage.getItem("select_rowdata");
            let rowtarget = JSON.parse(wps.PluginStorage.getItem("select_rowtarget"));
            console.log("select data:",data,rowtarget);
            dataObj =  JSON.parse(data);
            dataObj.row = rowtarget.Row;
            dataObj.col = rowtarget.Column;
            url = getMainURL() + "/kim/label/printCastingLoss.action";
            ActionJS.AjaxPostSP(url,dataObj,function(result){
				console.log("printCastingLoss:",result);
                //AlertJS.Message(result.ErrorMessage);
                if(result.errorCode != 1000 && result.errorCode != 1008){
                    alert(result.errorMsg)
                }else if(result.errorCode == 1008){
                    //alert("修正:"+result.errorMsg)
                    let curSheet = wps.EtApplication().ActiveSheet;
                    let targetSTRING = wps.PluginStorage.getItem("select_rowtarget");
	                let Target  = $.parseJSON( targetSTRING );
                    if(result.totalWeight && result.totalWeight.length > 0){
                        // 第17列是回金树
                        curSheet.Cells.Item(Target.Row,17).Formula = result.totalWeight;
                    }
                    if(result.totalWeight_exp && result.totalWeight_exp.length > 0){
                        // 第17列是回金树
                        curSheet.Cells.Item(Target.Row,17).Formula = result.totalWeight_exp;
                    }
                    if(result.boxWeight_exp && result.boxWeight_exp.length > 0){
                        // 第19列是碎金
                        curSheet.Cells.Item(Target.Row,19).Formula = result.boxWeight_exp;
                    }
                }
			});

            break;
        case "btnPrintMixKGold":
            data = wps.PluginStorage.getItem("any_select_rowdata");
            //console.log("select data:",data);
            // 检查补口列 16列是否为公式
            
            let curSheet = wps.EtApplication().ActiveSheet;
            let targetSTRING = wps.PluginStorage.getItem("select_rowtarget");
            let Target  = $.parseJSON( targetSTRING );

            dataObj =  JSON.parse(data);
            //console.log("a",curSheet.Cells.Item(Target.Row,16).Formula)
            if(curSheet.Cells.Item(Target.Row,16).Formula.indexOf("IF(") < 0){
                alert("补口公式不见了!!!! 再检查一下呗!!");
                return ;
            }

            url = getMainURL() + "/kim/label/mixKgold.action";
            ActionJS.AjaxPostSP(url,dataObj,function(result){
                console.log(result);
                //AlertJS.Message(result.ErrorMessage);
                if(result.errorCode != 1000 && result.errorCode != 1008){
                    alert(result.errorMsg)
                }else if(result.errorCode == 1008){
                    //alert("修正:"+result.errorMsg)
                   
                    // 第15列是足金
                    curSheet.Cells.Item(Target.Row,15).Formula = result.errorMsg;
                }
                
            });

            break;
        case "btnPrintProductLabel":
            data = wps.PluginStorage.getItem("any_select_rowdata");
            //console.log("select data:",data);
            dataObj =  JSON.parse(data);
            url = getMainURL() + "/kim/label/printProductWeight.action";
            ActionJS.AjaxPostSP(url,dataObj,function(result){
				console.log(result);
			});

            break;
        case "btnPrintStoreInLabel":
            data = wps.PluginStorage.getItem("any_select_rowdata");
            console.log("select data:",data);
            dataObj =  JSON.parse(data);
            url = getMainURL() + "/kim/label/printAnyLabel.action";
            ActionJS.AjaxPostSP(url,dataObj,function(result){
                if(result.errorCode != 1000){
                    alert(result.errorMsg);
                }
            });

            break;
        case "btnAudioTips2":
            url = getMainURL() + "/esp32/audio";
            dataObj = {"name":"00001"};
            dataObj.access_token = access_token();
            ActionJS.AjaxPostSP(url,dataObj,function(result){
                if(result.errorCode != 1000){
                    alert(result.errorMsg);
                }
            });

            break;
        case "btnAudioCutTree":
            url = getMainURL() + "/esp32/audio";
            dataObj = {"name":"00009"};
            dataObj.access_token = access_token();
            ActionJS.AjaxPostSP(url,dataObj,function(result){
                if(result.errorCode != 1000){
                    alert(result.errorMsg);
                }
            });

            break;
        case "btnAudioFindGold":
            url = getMainURL() + "/esp32/audio";
            dataObj = {"name":"00007"};
            dataObj.access_token = access_token();
            ActionJS.AjaxPostSP(url,dataObj,function(result){
                if(result.errorCode != 1000){
                    alert(result.errorMsg);
                }
            });

            break;
        case "btnAudioCasting":
            url = getMainURL() + "/esp32/audio";
            dataObj = {"name":"00008"};
            dataObj.access_token = access_token();
            ActionJS.AjaxPostSP(url,dataObj,function(result){
                if(result.errorCode != 1000){
                    alert(result.errorMsg);
                }
            });

            break;
        case "btnAudioDelivery":
            url = getMainURL() + "/esp32/audio";
            dataObj = {"name":"00010"};
            dataObj.access_token = access_token();
            ActionJS.AjaxPostSP(url,dataObj,function(result){
                if(result.errorCode != 1000){
                    alert(result.errorMsg);
                }
            });

            break;
        case "btnLockTaskLabel":
            let bFlag = wps.PluginStorage.getItem("EnableLockTaskFlag")
            wps.PluginStorage.setItem("EnableLockTaskFlag", !bFlag);
            //wps.ribbonUI.InvalidateControl("btnLockTaskLabel")
            break;
        case "btnFindImage":
            wps.ShowDialog(GetUrlPath() + "/ui/findImage.html?mainURL="+getMainURL()+"&access_token="+access_token(), "查看图片", 1200 * window.devicePixelRatio, 960 * window.devicePixelRatio, false) 
             break;
        case "btnIsEnbable":
            {
                let bFlag = wps.PluginStorage.getItem("EnableFlag")
                wps.PluginStorage.setItem("EnableFlag", !bFlag)
                
                //通知wps刷新以下几个按饰的状态
                wps.ribbonUI.InvalidateControl("btnIsEnbable")
                wps.ribbonUI.InvalidateControl("btnShowDialog") 
                wps.ribbonUI.InvalidateControl("btnShowTaskPane") 
                //wps.ribbonUI.Invalidate(); 这行代码打开则是刷新所有的按钮状态
                break
            }
        case "btnShowDialog":
            wps.ShowDialog(GetUrlPath() + "/ui/dialog.html", "这是一个对话框网页", 400 * window.devicePixelRatio, 400 * window.devicePixelRatio, false)
            break
        case "btnShowTaskPane":
            {
                let tsId = wps.PluginStorage.getItem("taskpane_id")
                if (!tsId) {
                    let tskpane = wps.CreateTaskPane(GetUrlPath() + "/ui/taskpane.html")
                    let id = tskpane.ID
                    wps.PluginStorage.setItem("taskpane_id", id)
                    tskpane.Visible = true
                } else {
                    let tskpane = wps.GetTaskPane(tsId)
                    tskpane.Visible = !tskpane.Visible
                }
            }
            break
        case "btnApiEvent":
            {
                let bFlag = wps.PluginStorage.getItem("ApiEventFlag")
                let bRegister = bFlag ? false : true
                wps.PluginStorage.setItem("ApiEventFlag", bRegister)
                if (bRegister){
                    wps.ApiEvent.AddApiEventListener('NewWorkbook', OnNewDocumentApiEvent)
                }
                else{
                    wps.ApiEvent.RemoveApiEventListener('NewWorkbook', OnNewDocumentApiEvent)
                }

                wps.ribbonUI.InvalidateControl("btnApiEvent") 
            }
            break
        case "btnWebNotify":
            {
                let currentTime = new Date()
                let timeStr = currentTime.getHours() + ':' + currentTime.getMinutes() + ":" + currentTime.getSeconds()
                wps.OAAssist.WebNotify("这行内容由wps加载项主动送达给业务系统，可以任意自定义, 比如时间值:" + timeStr + "，次数：" + (++WebNotifycount), true)
            }
            break
        default:
            break
    }
    return true
}

function GetImage(control) {
    const eleId = control.Id
    switch (eleId) {
        case "btnRecycleBoxGold":
            return "images/1.svg"
        case "btnShowDialog":
            return "images/2.svg"
        case "btnShowTaskPane":
            return "images/3.svg"
        case "btnPrintProductLabel":
            return "images/productLabel.svg"
        case "btnPrintStoreInLabel":
            return "images/suoding.svg"
        case "btnLockTaskLabel":
            return "images/task.svg"
        case "btnPrintCastingLoss":
            return "images/sunhao.svg"    
        case "btnPrintMixKGold":
            return "images/chengzhong.svg"
        case "btnAudioTips":
            return "images/tips.svg"
        case "btnAudioCutTree":
            return "images/cut.svg"
        case "btnAudioFindGold":
            return "images/find.svg"
        case "btnAudioCasting":
            return "images/zhuzao.svg"               
        case "btnAudioDelivery":
            return "images/waimaikuaidi.svg" 
        case "btnFindImage":
                return "images/tupian.svg" 
            default:
            ;
    }
    return "images/newFromTemp.svg"
}

function OnGetEnabled(control) {
    const eleId = control.Id
    switch (eleId) {
        case "btnRecycleBoxGold":
            return true
            break
        case "btnShowDialog":
            {
                let bFlag = wps.PluginStorage.getItem("EnableFlag")
                return bFlag
                break
            }
        case "btnShowTaskPane":
            {
                let bFlag = wps.PluginStorage.getItem("EnableFlag")
                return bFlag
                break
            }
        case "btnLockTaskLabel":
            {
                //let bFlag = wps.PluginStorage.getItem("EnableFlag")
               // return bFlag
                break
            }
        default:
            break
    }
    return true
}

function OnGetVisible(control){
    return true
}

function OnGetLabel(control){
    const eleId = control.Id
    switch (eleId) {
        case "btnIsEnbable":
        {
            let bFlag = wps.PluginStorage.getItem("EnableFlag")
            return bFlag ?  "按钮Disable" : "按钮Enable"
            break
        }
        case "btnApiEvent":
        {
            let bFlag = wps.PluginStorage.getItem("ApiEventFlag")
            return bFlag ? "清除新建文件事件" : "注册新建文件事件"
            break
        }    
    }
    return ""
}

function OnNewDocumentApiEvent(doc){
    alert("新建文件事件响应，取文件名: " + doc.Name)
}


